package com.mindmax.wordmemory.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.mindmax.wordmemory.domain.InfoVocabulary;
import com.mindmax.wordmemory.mapper.InfoVocabularyMapper;
import com.mindmax.wordmemory.service.IInfoVocabularyService;
import com.ruoyi.common.oss.AliyunOss;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * 单词详情Service业务层处理
 *
 * @author cab
 * @date 2024-04-24
 */
@Slf4j
@Service
public class InfoVocabularyServiceImpl implements IInfoVocabularyService
{
    @Autowired
    private InfoVocabularyMapper infoVocabularyMapper;

    /**
     * 查询单词详情
     *
     * @param id 单词详情主键
     * @return 单词详情
     */
    @Override
    public InfoVocabulary selectInfoVocabularyById(Long id)
    {
        return infoVocabularyMapper.selectInfoVocabularyById(id);
    }

    /**
     * 查询单词详情列表
     *
     * @param infoVocabulary 单词详情
     * @return 单词详情
     */
    @Override
    public List<InfoVocabulary> selectInfoVocabularyList(InfoVocabulary infoVocabulary)
    {
        return infoVocabularyMapper.selectInfoVocabularyList(infoVocabulary);
    }

    /**
     * 新增单词详情
     *
     * @param infoVocabulary 单词详情
     * @return 结果
     */
    @Override
    public int insertInfoVocabulary(InfoVocabulary infoVocabulary)
    {
        return infoVocabularyMapper.insertInfoVocabulary(infoVocabulary);
    }

    /**
     * 修改单词详情
     *
     * @param infoVocabulary 单词详情
     * @return 结果
     */
    @Override
    public int updateInfoVocabulary(InfoVocabulary infoVocabulary)
    {
        return infoVocabularyMapper.updateInfoVocabulary(infoVocabulary);
    }

    @Override
    public int updateInfoVocabularyStoreId(Long fileStoreId, Long id) {
        return infoVocabularyMapper.updateInfoVocabularyStoreId(fileStoreId, id);
    }

    /**
     * 批量删除单词详情
     *
     * @param ids 需要删除的单词详情主键
     * @return 结果
     */
    @Override
    public int deleteInfoVocabularyByIds(Long[] ids)
    {
        return infoVocabularyMapper.deleteInfoVocabularyByIds(ids);
    }

    /**
     * 删除单词详情信息
     *
     * @param id 单词详情主键
     * @return 结果
     */
    @Override
    public int deleteInfoVocabularyById(Long id)
    {
        return infoVocabularyMapper.deleteInfoVocabularyById(id);
    }



    @Resource
    AliyunOss aliyunOss;
    @Override
    public Map<@Nullable Long, @Nullable String> genVoice(String ids) {
        Iterable<String>                        split               = Splitter.on(',').split(ids);
        Map<@Nullable Long, @Nullable String> m = Maps.newHashMap();

        split.forEach(id->{
            log.info("#### tts id: {}", id);
            long idLong = Long.parseLong(id);
            InfoVocabulary infoVocabulary = infoVocabularyMapper.selectInfoVocabularyById(Long.parseLong(id));
            if (null == infoVocabulary) {
                return;
            }
            String sentence = infoVocabulary.getSentence();
            log.info("#### tts sentence: {}", sentence);
            String audioFileLink = getAudioFileLink(sentence);
            String ossUrl             = aliyunOss.uploadByLocalFile(audioFileLink);
            log.info("#### tts audioFileLink to OSS: {}", ossUrl);
            m.put(idLong, ossUrl);

        });

        return m;
    }


    public static void main(String[] args) {
        String 你好 = getAudioFileLink("hello,where are you from");
        System.out.println("你好 = " + 你好);
    }
    public static String getAudioFileLink(String text) {
        String urlString = "https://user.api.hudunsoft.com/v1/alivoice/texttoaudio";
        String parameters = "client=web&source=335&soft_version=V4.4.0.0&device_id=0b8b0cf4d5da43f19d00b7123cbe9212&text=" + text +
                "&bgid=0&bg_volume=5&format=mp3&voice=ruoxi&volume=4&speech_rate=4&pitch_rate=4&title=" + text +
                "&token=0b8b0cf4d5da43f19d00b7123cbe9212&bg_url=";

        try {
            URL               url        = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
            connection.setRequestProperty("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
            connection.setRequestProperty("cache-control", "no-cache");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("origin", "https://www.luyinzhushou.com");
            connection.setRequestProperty("pragma", "no-cache");
            connection.setRequestProperty("priority", "u=1, i");
            connection.setRequestProperty("sec-ch-ua", "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"");
            connection.setRequestProperty("sec-ch-ua-mobile", "?0");
            connection.setRequestProperty("sec-ch-ua-platform", "\"Windows\"");
            connection.setRequestProperty("sec-fetch-dest", "empty");
            connection.setRequestProperty("sec-fetch-mode", "cors");
            connection.setRequestProperty("sec-fetch-site", "cross-site");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = parameters.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    String     content      = response.toString();
                    JSONObject jsonResponse = new JSONObject(content);
                    if (jsonResponse.getInt("code") == 0) {
                        return jsonResponse.getJSONObject("data").getStr("file_link");
                    } else {
                        log.error(("Failed to get file link: " + jsonResponse.getStr("message")));
                    }
                }
            } else {
                log.error("HTTP request failed with code: " + responseCode);
            }
        } catch (Exception e) {
            log.error("getAudioFileLink error", e);
        }
        return null;
    }
}
